﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TA.Turbo
{
	internal class FileUploadRequestReader : TextReader
	{
		internal FileUploadRequestReader(FileUploadRequestStream stream, Encoding encoding)
		{
			this._stream = stream;
			this._encoding = encoding;
		}
		public override string ReadLine()
		{
			StringBuilder sb = new StringBuilder();
			string block = null, toAdd = null;
			int newLinePos = -1;
			do
			{
				int numBytesRead = this._stream.Peek(this._data, 0, this._data.Length);
				if (numBytesRead == 0) break;

				block = this._encoding.GetString(this._data, 0, numBytesRead);

				newLinePos = block.IndexOf("\r");
				if (newLinePos == -1)
					block.IndexOf("\n");

				if (newLinePos == -1)
					toAdd = block;
				else
					toAdd = block.Substring(0, newLinePos);
				sb.Append(toAdd);

				int usedBytes = this._encoding.GetByteCount(toAdd);
				this._stream.Skip(usedBytes);
			}
			while (newLinePos == -1);

			if (newLinePos != -1)
			{
				if (block[toAdd.Length] == '\n')
					this._stream.Skip(this._encoding.GetByteCount("\n"));
				else if (block[toAdd.Length] == '\r')
				{
					if (block.Length == toAdd.Length + 1)
						this._stream.Skip(this._encoding.GetByteCount("\r"));
					else
						this._stream.Skip(this._encoding.GetByteCount("\r\n"));
				}
			}

			return sb.ToString();
		}
		FileUploadRequestStream _stream;
		Encoding _encoding;
		byte[] _data = new byte[1024];
	}
}
